package cool.webstudy.admin.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import cool.webstudy.admin.service.BaseLoggerService;
import cool.webstudy.common.model.dto.logger.BaseLoggerDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author think
 * @date 2024/12/2 15:46
 * @description: 基础日志服务实现类
 */
@Service
public class BaseLoggerServiceImpl implements BaseLoggerService {
    @Autowired
    private KafkaTemplate kafkaTemplate;

    /**
     * @param topic 主题
     * @param key
     * @param dto   待发送的消息
     * @return void
     * @description: 将日志信息发送到kafka中
     */
    @Override
    public Boolean sendMessage(BaseLoggerDTO dto, String topic, String key) {
        if (Objects.isNull(dto)) {
            return false;
        }
        try {
            //将dto序列化成json字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(dto);
            kafkaTemplate.send(topic, 0, key, json);
        } catch (Exception e) {
            //TODO 将日志写入磁盘日志文件中，在UTIL中创建保存日志文件至磁盘的工具类
            return false;
        }
        return true;
    }
}
